package com.hhss.qishi.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.hhss.qishi.entity.JsonResult;
import com.hhss.qishi.entity.input.Setup;
import com.hhss.qishi.entity.rejson.JsonResponse;
import com.hhss.qishi.utils.ConvertObjectUtil;
import com.hhss.qishi.utils.VerfiyCodeUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 配置页控控制器
 */
@RestController
@RequestMapping("/setup")
public class SetupController {
    /**
     * 配置页登录用户名
     */
    @Value("${QSApplication.setup.userName}")
    private String USER_NAME;

    /**
     * 配置页登录密码
     */
    @Value("${QSApplication.setup.password}")
    private String PASSWORD;

    /**
     * 数据库地址
     */
    @Value("${spring.datasource.url}")
    private String DB_URL;

    /**
     * 数据库用户
     */
    @Value("${spring.datasource.username}")
    private String DB_USER_NAME;

    /**
     * 数据库密码
     */
    @Value("${spring.datasource.password}")
    private String DB_PASSWORD;

    /**
     * setup登录
     * @param httpServletRequest
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public String Login(HttpServletRequest httpServletRequest, String userName , String password){
        JsonResult result = new JsonResult();
        if(!VerfiyCodeUtil.verify(httpServletRequest, "tryCode")){
            result.setResult("验证码错误");
            result.setStatus("2000001");
            return ConvertObjectUtil.toJson(result);
        }
        if(!checkSetupLogin(userName, password)){
            result.setResult("用户名密码错误");
            result.setStatus("2000002");
            return ConvertObjectUtil.toJson(result);
        }

        result.setResult("./config.html");
        result.setStatus("1000000");
        return ConvertObjectUtil.toJson(result);
    }

    /**
     * 接收参数进行初始化
     * @param setup
     * @return
     */
    @RequestMapping(value = "/config", method = RequestMethod.POST)
    public String config(Setup setup){

        System.out.println("setup:" + setup.toString());
        return null;
    }

    /**
     * 获取配置参数
     * @return
     */
    @RequestMapping(value = "/config", method = RequestMethod.GET)
    public String config(){
        Setup setup = new Setup();
        setup.setDbAddress(DB_URL);
        setup.setUserName(DB_USER_NAME);
        setup.setPassword(DB_PASSWORD);
        return ConvertObjectUtil.toJson(setup);
    }

    @RequestMapping(value = "database/init")
    public JsonResponse initSetup(){

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try{

            List<String> fileNames = new ArrayList<>();

            org.springframework.core.io.Resource[] resources = resolver.getResources("classpath:_sql/*.sql");
            for (Resource resource : resources) {
                String filename = resource.getFilename();
                fileNames.add(filename);
            }

            // 建立连接
            Connection conn = DriverManager.getConnection(DB_URL, DB_USER_NAME, DB_PASSWORD);

            // 创建ScriptRunner，用于执行SQL脚本
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.setLogWriter(null);
            // 执行SQL脚本

            for (String fileName : fileNames) {
                runner.runScript(Resources.getResourceAsReader("_sql/" + fileName + ".sql"));
            }

            // 关闭连接
            conn.close();

            // 若成功，打印提示信息
            System.out.println("====== SUCCESS ======");
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }

        return JsonResponse.success("执行成功");
    }


    /**
     * 检查setup的用户名密码是否正确
     * @param userName
     * @param password
     * @return
     */
    private boolean checkSetupLogin(String userName, String password){
        if(USER_NAME.equals(userName) && PASSWORD.equals(password)){
            return true;
        }
        return false;
    }



}
